package com.songtech.server.netty.handler;

import com.songtech.server.frame.protocal.analyse.Analyze;
import com.songtech.server.frame.push.ChannelCacheManager;
import com.songtech.server.frame.utils.AnalyzeUtils;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelFutureListener;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Service;

/**
 * Create By YINN on 2018/4/2 11:21
 * Description : 业务处理器
 */

@Service("serverHandler")
@Scope("prototype")
@ChannelHandler.Sharable
public class ServerHandler extends ChannelInboundHandlerAdapter {


    /**
     * 协议分析器
     * */
    @Autowired
    private Analyze analyze;

    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {

//        String imei = AnalyzeUtils.getIMEI((String) msg);

        super.channelActive(ctx);
    }

    @Override
    public void channelInactive(ChannelHandlerContext ctx) throws Exception {
        super.channelInactive(ctx);
    }

    /**
     * Created by YINN on 2018/4/2 11:24.
     * @Description : 对于每个传入的消息都要调用,将消息打印进控制台
     * @param ctx
     * @param msg
     * @Result :
     */
    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {

        String imei = AnalyzeUtils.getIMEI((String) msg);

        //添加管道缓存 ...实时更新
        ChannelCacheManager.addChannel(imei, ctx.channel());

        long s = System.currentTimeMillis();

        analyze.spiltMsg((String) msg);

        long e = System.currentTimeMillis();

        System.out.println("消耗时间" + (e - s));
//        System.out.println(ctx.getClass().getName());
//        super.channelRead(ctx, msg);
//        ByteBuf in = (ByteBuf) msg;
//        System.out.println("Server received:" + in.toString(CharsetUtil.UTF_8));
//        //将接收到的消息写给发送者，而不冲刷出战消息
//        ctx.write(in);
    }

    @Override
    public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
//        super.channelReadComplete(ctx);
        //将缓存区中剩余字节，在下次调用writeAndFlush方法是将会尝试写入socket
        //将剩余字节冲刷到远程节点，并且关闭该管道
        ctx.writeAndFlush(Unpooled.EMPTY_BUFFER);
//                .addListener(ChannelFutureListener.CLOSE);
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
//        super.exceptionCaught(ctx, cause);
        cause.printStackTrace();
        ctx.close();
    }
}
